by Ron Schwarz
Operators are keywords and characters that tell the VBScript interpreter to act upon the values contained in variables, literals, and expressions.
This chapter examines arithmetic, string, comparison, and logical operator groups. Each group is discussed in a separate section, and each section contains a short table listing the operators in that group.
In this chapter
In most cases, you can view operators as behaving identically on expressions, variables, and literals. One important exception is the assignment operatorùyou can only assign a value to a variable. (You can have a numeric literal or an expression on the left side of an equals sign, but only when performing a testùfor example, If (A + B) = (C + D) Then...)
Much of your VBS code depends on logical operations. A good understanding of the more commonly-used operators is essential. If you come from a background of programming in other languages, you've undoubtedly got a good grasp of the subject, and only need to brush up on VBS syntax. If you're just getting into programming VBS from a background of HTML programming, it's time to dig in, and learn the principles of logical testing and bitwise operations.
Operator Precedence
Throughout this chapter, you'll see extensive use of parentheses in example code. While it's frequently possible to rely on Operator Precedence rules (described below), you may find that your code is much more readable and you spend much less time debugging your apps if you are not overly sparing in your use of parentheses.
Parentheses always override Operator Precedence rules. And, expressions are evaluated from the inside out, starting with the innermost set(s) of parentheses. Coercing evaluation this way eliminates ambiguityùboth to you and to the VBS script execution engine.
If you neglect to use sets of parentheses to force evaluation to take place according to your rules, VBS falls back on its default Operator Precedence rules. According to these built-in rules, the order of evaluation is:
Arithmetic operators (see following) Comparison operators (evaluated left-to-right) Logical operators (see following) Arithmetic and logical operators, unlike comparison operators, are evaluated in specific order. The evaluation order for arithmetic operators is:
Exponentiation Unary negation Multiplication Division Integer division Modulo arithmetic Addition Subtraction String Concatenation (not an arithmetic operator, but evaluated in same order sequence) The evaluation order for logical operators is:
Logical negation Logical conjunction Logical disjunction Logical exclusion Logical equivalence Logical implication
The arithmetic operators are used with numeric variables and literals and expressions. (Since VBS at the moment has no constants, they are not an issue here.) The plus sign (+) can also be used as a string concatenation operator, but this usage is obsolete and should be used sparingly.
The following table lists the Arithmetic Operators:
Operator | Definition |
- | Unary negation |
* | Multiplication |
/ | Division |
\ | Integer division |
Mod | Modulo arithmetic |
+ | Addition |
- | Subtraction |
^ | Exponentiation |
In addition to the arithmetic operators discussed in this chapter, VBS offers a rich selection of math functions. These are covered in greater detail in Chapter 22, "VBScript Language Elements."
The Unary Negation (û) operator designates the negative value of a variable, number, or expression. Please note that the minus character is also used as the subtraction operator and is discussed later in this chapter. The following example returns û10 in B:
A = 10
B = -A
The Asterisk (*) character is used to multiply two values according to the following syntax:
Total = Item * Quantity
The forward slash (/) is used when dividing one value by another. It returns either an integer or floating point value, as dictated by the actual operation. For coerced integer division, see the integer division operator description.
The Division Operator is demonstrated in the following example.
UnitPrice = TotalPrice / Quantity
The integer division (\) operator is used the same way as the division operator. However, it truncates any remainder, and only returns the integer part of the result.
The following example returns 3:
IntResult = 10 \ 3
The Modulo Arithmetic (Mod) operator is used to return the non-integer part of a division operation. The following example returns 1:
IntResult = 10 Mod 3
The plus sign (+) is used as the Addition Operator. As mentioned earlier, it can also be used as a string concatenation operator, but this usage should be avoided unless there is a specific need for the peculiarities it introduces. (When using the + sign between two variables, the expression can be rendered as either an addition operation or a concatenation operation, depending on the values and types of the two variables. Because of the uncertainties this creates, it's generally best to reserve use of the + sign for addition, and the & for concatenation.)
The following example returns 10 in A:
A = 5 + 5
The minus sign (û) is used as the Subtraction Operator. It is important to avoid confusing this with its other use (as a unary negation operator). The following example returns 5 in A:
A = 10 - 5
The Exponentiation Operator (^) is used to raise one value to the power of another. The following example returns 256:
Result = 2 ^ 8
Unlike multiplication, you must be careful about where you place exponentiation expressionsùreversing the order produces dramatically different results. The following example returns 64:
Result = 8 ^ 2
There is only one String Operator: the & string concatenation operator. Don't think of this as a real limitation, however. Unlike numbers, strings aren't really subject to "operations," per seùfor example, you don't multiply one word by another. However, there is a rich set of string manipulation functions, and the comparison operators (described later in this chapter) apply to most variable types, including strings.
The ampersand (&) is used for concatenating strings. Concatenation simply consists of joining two strings together. Concatenation does not join one string to anotherùit returns a third string that represents the result of the operation. The original strings are left intact. The following example returns Ron's Computer:
MyComputer = "Ron's" & " " & "Computer"
In the preceding example, we used two concatenation operations in one expression. This is perfectly legalùeach operation only works on two strings. The + sign can also be used to concatenate strings but its use is generally discouraged.
The Comparison Operators, as show in the following table, are used when testing expressions and variables against each other or against other conditions such as True or False.
Operator | Definition |
= | Equality |
<> | Inequality |
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
Is | Object equivalence |
The equals sign (=) is used as the Equality Operator. It is also used as an Assignment Operator.
The = Assignment Operator
You may have noticed that there is no section for assignment operators and no entry in any table for the equals sign in its assignment operator mode. This is due to some BASIC arcanaùthe equals sign is, strictly speaking, part of the Let statement. However, use of Let is optional in VB, and the only time you're apt to see it in use is when non-VB code (for example, other non-Microsoft dialects of BASIC) is ported over to VBS. In VB and VBS, X = 10 is functionally identical to (and more readable than) Let X = 10.
(The Let X = 10 syntax should not be confused with Property Let settings in VB, which are not implemented in VBScript.)
The equals sign is used when testing one expression against another for equality. As with all comparison operators, the result is an implicit Boolean (True or False) result. If A = B Then is equivalent to the following code:
If (A = True) And (B = True) Then
EndIf
Due to the way VBS handles these tests, you do not have to test for explicit True, and, as demonstrated in the following code snippet, you don't even have to use the equality operator in some cases.
If A Then
EndIf
In the preceding example, as long as A is non-zero (presuming that A is a numeric variable) the test succeeds. If you need to test against True (or any other specific value), you need to use the equals sign, as in the following:
If A = 25 Then
EndIf
The < and > characters combine to form the Inequality Operator. They function opposite to the equality operator. The following example demonstrates their use:
If CreditStatus <> FlaggedAccount Then
EndIf
In this example, as long as the two variables are not equal, the test passes.
The inequality operator can also be used on strings. It performs a test based on ASCII value, which is case-sensitive. If you need to perform a case-insensitive test, you must use either Lcase or Ucase to assure that both values are of the same case. If the strings do not match, the result is True.
The < character is used as the Less Than Operator. If the expression on the left side of the less than operator is less than the expression on the right, the test passes. In the following example, as long as the value in RPM is less than the value in Redline, the test passes:
If RPM < Redline Then
EndIf
The less than operator can also be used on strings. It performs a test based on ASCII value, which is case-sensitive. If you need to perform a case-insensitive test, you must use either Lcase or Ucase to assure that both values are of the same case. Be careful, as differences in length can affect the results. This can be a problem when strings contain numeric values, and different numbers of leading zeros further complicate matters.
The Greater Than Operator (>) is the opposite of the less than operator. If the expression on the left side of the > is higher, the test passes. In the following example, as long as Balance is higher than Limit, the test passes:
If Balance > Limit Then
EndIf
The greater than operator can also be used on strings. It performs a test based on ASCII value, which is case-sensitive. If you need to perform a case-insensitive test, you must use either Lcase or Ucase to assure that both values are of the same case. The same concerns mentioned for the less than operator also apply here.
The Less Than or Equal to Operator (<=) can also be used on strings. It performs a test based on ASCII value, which is case-sensitive. If you need to perform a case-insensitive test, you must use either Lcase or Ucase to assure that both values are of the same case. The same concerns mentioned for the less than operator also apply here.
This example will pass if the value in Amount is less than, or equal to the amount in Limit:
If Amount <= Limit Then
EndIf
The Greater Than or Equal to Operator (>=) can also be used on strings. It performs a test based on ASCII value, which is case-sensitive. If you need to perform a case-insensitive test, you must use either Lcase or Ucase to assure that both values are of the same case. The same concerns mentioned for the less than operator also apply here.
In this example, the test will pass if the value in Age is greater than or equal to the value in Minimum:
If Age >= Minimum Then
Endif
Object Equivalence
The Is keyword is the Object Equivalence Operator. It tests two objects or object variables to if they are refer to the same object. The following code snippet demonstrates a test of Object Equivalence:
Match= Handy Is LongFormName.LongControlName
In this test, if Handy is an object variable that has been previously Set to a reference to LongFormName.LongControlName, Match will return True, otherwise, it will return False.
Logical Operators
This table defines the Logical Operators:
Operator | Definition |
Not | Logical negation |
And | Logical conjunction |
Or | Logical disjunction |
Xor | Logical exclusion |
Eqv | Logical equivalence |
Imp | Logical implication |
The logical operators apply to Boolean expressions. The elements of a Boolean expression can be of any data typeùit's not necessary to build a Boolean expression out of Boolean variables.
A Boolean Expression is an expression that returns either True or False (-1 or 0) as its result.
The And and Or operators wear two hats: they are used in simple tests of expressions and in bitwise Boolean operations. The differences are noted in the following respective sections.
Each logical operator description contains a truth table that shows the results produced by all possible bit combinations.
A Truth Table is a list of all possible operations and results for a specific operator.
One additional factor comes into play with logical operations. When any value contains Null, the result is also Null. Null propagates through the operation. This is not shown in the truth tables, but should be taken into consideration if there is a possibility that any of your values might contain Null.
Logical Negation (the Not keyword) is similar to unary negation, but, like all logical operators, is carried out on the bit level rather than on the value of the expression. It's easy to fall into the trap of using Not when testing expressions, and finding that things aren't working as they should. Not reverses all the bits in a variable, and is generally used against either True or False in Boolean tests.
A common programming error is to look at the Not operator in the same context as the And and Or operators. While we can use And and Or to build a logical testing expression, we cannot do so cavalier with Not.
For example, the following code does not work correctly:
If (Balance < Limit) And (Lastname Not "Smith") Then
EndIf
For one thing, we can't "NOT" a string. And, even if we use numeric values, we'd still have a large unpredictability factor.
There are some nifty uses for this operator, though. A variable (or a property) that needs to toggle between True and False can be easily managed with one simple line of code. The following line of code toggles the value of the Direction variable between True and False. This is much simpler than a complex "If Direction = True Then Direction = False Else..." block of code.
Direction=Not Direction 'reverse direction
The reason for this is simple: when we reverse the bits in False (0), we end up with True (û1), and vice versa.
Here is the Logical Negation Operator's truth table:
Truth Table for Logical Negation
Expression | Result |
False | True |
True | False |
The And keyword is used as the Logical Conjunction Operator in VBScript. As with the logical disjunction (Or) operator, it has dual uses. You can apply any logical test against a clause of one expression And another, or you can use And to return a value representing a bitwise (bitwise means that the two values are tested one bit at a time) "Anding" of two values.
The following example passes if both expressions evaluate to an implicit True:
If (Total < Limit) And (AccountStatus = Current)Then
EndIf
The next example returns 127 in C, since the set bits that are common to both A and B equal 127:
A = 127
B = 255
C = A And B
This is the truth table for the Logical Conjunction Operator:
First Expression | Second Expression | Result |
False | False | False |
False | True | False |
True | False | False |
True | True | True |
Or is used as the Logical Disjunction Operator. Like And, it is used when testing expressions and also for bitwise Boolean operations.
The comparison test in the following example passes if either of the expressions evaluate to an implicit True:
If (Moves > GameLimit) or (GameTime > TimeOut) then
EndIf
The next example always returns the lowercase form of whatever (single letter) string literal is passed:
LowerCase = Chr(Asc("A") or 32)
Here is the Logical Disjunction truth table:
First Expression | Second Expression | Result |
False | False | False |
False | True | True |
True | False | True |
True | True | True |
The Xor (Exclusive Or) keyword is used as the Logical Exclusion Operator. The logical exclusion operator is similar to the Or operator, with one significant difference. Whereas Or evaluates when either or both bits are set (remember, we're comparing values one bit at a time), Xor evaluates when only one bit is setùhence, its "exclusive" qualification.
The Xor Logical Exclusion Operator is frequently used for simple encryption routines, since a byte Xored by another number produces a number that is restored when Xored by the same number. By Xoring a string one character at a time against each character of a password string, an encrypted string results. And, when Xoring the encrypted string by the same password, the plaintext string is restored.
It is interesting to note that any value Xored with itself results in False.
The first routine in Listing 16.1 encrypts the string contained in PlainText, and places the encrypted value in CryptText.
The second routine reverses the process, and places the decrypted string in NewText.
Listing 16.1 Logical Exclusion Example
The Logical Exclusion truth table follows:
First Expression | Second Expression | Result |
False | False | False |
False | True | True |
True | False | True |
True | True | False |
The Eqv keyword is used as the Logical Equivalence Operator. This operation is similar to And, but, in addition to evaluating when both bits are set, it also evaluates when both bits are not set. If both bits are the same (either True or False) the expression passes evaluation. Here is the Logical Equivalence Operator truth table:
First Expression | Second Expression | Result |
False | False | True |
False | True | False |
True | False | False |
True | True | True |
Logical Implication
Imp is used as the Logical Implication Operator. If identical bits in both expressions are True or if bits in the righthand expression are True, the operation evaluates as True. Here's the Logical Implication truth table:
First Expression | Second Expression | Result |
False | False | True |
False | True | True |
True | False | False |
True | True | True |
Operators are used in every aspect of VBScript programming. Check Chapters 11-20 for general coverage of language features. And, specifically, consult these chapters for more information:
| Previous Chapter | Next Chapter |
| Search | Table of Contents | Book Home Page | Buy This Book |
| Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.